# @FileName  :  student.py
# @Time      :  2025/7/29 11:05
# @Author    :  Ayanami
# @info      :  学生相关API接口

from typing import Optional
from fastapi import APIRouter, HTTPException, Query, Path
from app.crud.student import student_crud
from app.schemas.student import (
    StudentCreate,
    StudentUpdate,
    StudentResponse,
    StudentListResponse,
    StudentDetailResponse
)
from app.models.models import Gender

router = APIRouter(prefix="", tags=["学生管理"])


@router.post("/", response_model=StudentResponse, summary="创建学生")
async def create_student(student_data: StudentCreate):
    """创建新学生"""
    # 检查学号是否已存在
    existing_student = await student_crud.get_by_student_id(student_data.student_id)
    if existing_student:
        raise HTTPException(status_code=400, detail="学号已存在")

    # 检查身份证号是否已存在
    existing_id_card = await student_crud.get_by_id_card(student_data.id_card)
    if existing_id_card:
        raise HTTPException(status_code=400, detail="身份证号已存在")

    try:
        student = await student_crud.create(student_data)
        return StudentResponse.model_validate(student)
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"创建学生失败: {str(e)}")


@router.get("/", response_model=StudentListResponse, summary="获取学生列表")
async def get_students(
        skip: int = Query(0, ge=0, description="跳过记录数"),
        limit: int = Query(20, ge=1, le=100, description="每页记录数"),
        search: Optional[str] = Query(None, description="搜索关键词(姓名/学号/手机/身份证)"),
        area_id: Optional[int] = Query(None, description="地区ID"),
        gender: Optional[Gender] = Query(None, description="性别"),
        is_verified: Optional[bool] = Query(None, description="实名认证状态")
):
    """获取学生列表"""
    students, total = await student_crud.get_list(
        skip=skip,
        limit=limit,
        search=search,
        area_id=area_id,
        gender=gender,
        is_verified=is_verified
    )

    student_responses = [StudentResponse.model_validate(student) for student in students]

    return StudentListResponse(total=total, items=student_responses)


@router.get("/{student_id}", response_model=StudentDetailResponse, summary="获取学生详情")
async def get_student(
        student_id: int = Path(..., description="学生ID")
):
    """获取学生详情"""
    student = await student_crud.get_by_id(student_id)
    if not student:
        raise HTTPException(status_code=404, detail="学生不存在")

    # 构建详细响应
    student_dict = StudentDetailResponse.model_validate(student).model_dump()
    if student.area:
        student_dict["area_name"] = student.area.name

    return StudentDetailResponse(**student_dict)


@router.put("/{student_id}", response_model=StudentResponse, summary="更新学生信息")
async def update_student(
        student_data: StudentUpdate,
        student_id: int = Path(..., description="学生ID")
):
    """更新学生信息"""
    # 检查学生是否存在
    existing_student = await student_crud.get_by_id(student_id)
    if not existing_student:
        raise HTTPException(status_code=404, detail="学生不存在")

    # 如果更新身份证号，检查是否重复
    if student_data.id_card and student_data.id_card != existing_student.id_card:
        duplicate_student = await student_crud.get_by_id_card(student_data.id_card)
        if duplicate_student:
            raise HTTPException(status_code=400, detail="身份证号已存在")

    try:
        updated_student = await student_crud.update(student_id, student_data)
        if not updated_student:
            raise HTTPException(status_code=404, detail="学生不存在")

        return StudentResponse.model_validate(updated_student)
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"更新学生失败: {str(e)}")


@router.delete("/{student_id}", summary="删除学生")
async def delete_student(
        student_id: int = Path(..., description="学生ID")
):
    """删除学生"""
    success = await student_crud.delete(student_id)
    if not success:
        raise HTTPException(status_code=404, detail="学生不存在")

    return {"message": "学生删除成功"}


@router.get("/student-id/{student_id}", response_model=StudentDetailResponse, summary="根据学号获取学生")
async def get_student_by_student_id(
        student_id: str = Path(..., description="学号")
):
    """根据学号获取学生信息"""
    student = await student_crud.get_by_student_id(student_id)
    if not student:
        raise HTTPException(status_code=404, detail="学生不存在")

    student_dict = StudentDetailResponse.model_validate(student).model_dump()
    if student.area:
        student_dict["area_name"] = student.area.name

    return StudentDetailResponse(**student_dict)


@router.patch("/{student_id}/verify", summary="实名认证学生")
async def verify_student(
        student_id: int = Path(..., description="学生ID")
):
    """实名认证学生"""
    success = await student_crud.verify_student(student_id)
    if not success:
        raise HTTPException(status_code=404, detail="学生不存在")

    return {"message": "学生实名认证成功"}


@router.patch("/{student_id}/study-hours", summary="更新学习时长")
async def update_study_hours(
        hours: int,
        student_id: int = Path(..., description="学生ID")
):
    """更新学生学习时长"""
    if hours <= 0:
        raise HTTPException(status_code=400, detail="学习时长必须大于0")

    success = await student_crud.update_study_hours(student_id, hours)
    if not success:
        raise HTTPException(status_code=404, detail="学生不存在")

    return {"message": f"学习时长更新成功，增加{hours}小时"}


@router.patch("/{student_id}/honors", summary="更新荣誉数量")
async def update_honors_count(
        count: int,
        student_id: int = Path(..., description="学生ID")
):
    """更新学生荣誉数量"""
    success = await student_crud.update_honors_count(student_id, count)
    if not success:
        raise HTTPException(status_code=404, detail="学生不存在")

    return {"message": f"荣誉数量更新成功，增加{count}个"}